package com.guiyang.practice.mess1.service.impl;

import com.guiyang.practice.mess1.entity.MessageType;
import com.guiyang.practice.mess1.mapper.MessageTypeMapper;
import com.guiyang.practice.mess1.service.MessageTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class MessageTypeServiceImpl implements MessageTypeService {

    @Autowired
    private MessageTypeMapper messageTypeMapper;

    @Override
    public List<MessageType> getAllTypes() {
        return messageTypeMapper.findAll();
    }

    @Override
    public List<MessageType> getEnabledTypes() {
        return messageTypeMapper.findAllEnabled();
    }

    @Override
    public MessageType getTypeById(Long id) {
        return messageTypeMapper.findById(id);
    }

    @Override
    public boolean addType(MessageType messageType) {
        // 检查类型编码是否已存在
        if (isTypeCodeExists(messageType.getTypeCode(), null)) {
            throw new RuntimeException("类型编码已存在");
        }
        return messageTypeMapper.insert(messageType) > 0;
    }

    @Override
    public boolean updateType(MessageType messageType) {
        // 检查类型编码是否已存在（排除当前记录）
        if (isTypeCodeExists(messageType.getTypeCode(), messageType.getId())) {
            throw new RuntimeException("类型编码已存在");
        }
        return messageTypeMapper.update(messageType) > 0;
    }

    @Override
    public boolean disableType(Long id) {
        return messageTypeMapper.disable(id) > 0;
    }

    @Override
    public boolean enableType(Long id) {
        return messageTypeMapper.enable(id) > 0;
    }

    @Override
    public boolean isTypeCodeExists(String typeCode, Long excludeId) {
        MessageType existingType = messageTypeMapper.findByTypeCode(typeCode);
        if (existingType == null) {
            return false;
        }
        // 如果excludeId不为null，且找到的记录ID与excludeId相同，表示是同一记录
        return excludeId == null || !existingType.getId().equals(excludeId);
    }
}